﻿namespace AzureCamp.RssAggregatorBusiness.Queue
{
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using Microsoft.Samples.ServiceHosting.StorageClient;
    using System;

    public class QueueUpdateFeed
    {
        private StorageAccountInfo account;
        private QueueStorage service;
        private MessageQueue queue;

        public MessageQueue Queue
        {
            get
            {
                if (!queue.DoesQueueExist())
                {
                    queue.CreateQueue();
                } 
                return this.queue;
            }
            set { this.queue = value; }
        }
        public QueueUpdateFeed()
        {
            account = StorageAccountInfo.GetDefaultQueueStorageAccountFromConfiguration();
            service = QueueStorage.Create(account);
            queue = service.GetQueue("queueUpdateBlob");
            if (!queue.DoesQueueExist())
            {
                queue.CreateQueue();
            }
        }

        public void PutUpdateFeed()
        {
            Message msg = new Message("");
            queue.PutMessage(msg);
        }

        public Message GetUpdateFeed()
        {
            Message msg = queue.GetMessage();
            queue.DeleteMessage(msg);
            return msg;
        }

        public IEnumerable<Message> GetBlobsToDelete()
        {
            int approximateCount = queue.ApproximateCount();
            if (approximateCount > 0)
            {
                IEnumerable<Message> messages = queue.GetMessages(approximateCount);
                foreach (Message m in messages)
                {
                    queue.DeleteMessage(m);
                }
                return messages;
            }
            return new Collection<Message>();
        }

    }
}
